package com.fzq.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzq.util.RedisMapper;
import com.fzq.util.ResponseResult;
import com.fzq.util.TokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 退出成功处理器
 */
@Component
public class SimpLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private RedisMapper redisMapper;


    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        //获得请求头中的token
        String token=request.getHeader("token");
        //解析出token中的帐号
        String account= TokenUtil.getUserName(token);
        //删除redis中对应的键和权限
        redisMapper.delKey(account+":login:token");
        redisMapper.delKey(account+":author");

        //返回成功状态码
        ObjectMapper objectMapper=new ObjectMapper();
        //响应请求转码
        response.setContentType("application/json;charset=UTF-8");
        ResponseResult<Void> responseResult=new ResponseResult<Void>(200, "退出成功。。。");
        String json=objectMapper.writeValueAsString(responseResult);
        //输出json字符串到客户端
        PrintWriter printWriter =response.getWriter();
        printWriter.print(json);
        printWriter.flush();
        printWriter.close();

    }
}
